package top.healthylife.controller;/*
 *@Author GaoZeXi
 *@Created time 2020/4/15 6:33
 *@Description:
 * Step by Step  and Stand on,  You Are The Best Investment!!!
 */

import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyuncs.exceptions.ClientException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;
import top.healthylife.constant.MessageConstant;
import top.healthylife.constant.RedisMessageConstant;
import top.healthylife.domain.Order;
import top.healthylife.entity.Result;
import top.healthylife.service.OrderService;
import top.healthylife.utils.SMSUtils;

import java.util.Map;

/**
 * 体检预约
 * @author GaoZeXi
 * @date 2020-4-15 06:34:04
 */
@RestController
@RequestMapping("/order")
public class OrderController {
    @Reference
    private OrderService orderService;

    @Autowired
    private JedisPool jedisPool;
    @RequestMapping("/submit")
    public Result submitOrder(@RequestBody Map map){
        String telephone = (String) map.get("telephone");
        //校验验证码
        String codeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        //用户输入的验证码
        String validateCode = (String) map.get("validateCode");
        if (codeInRedis==null||validateCode==null||!codeInRedis.equals(validateCode)) {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
        Result result =null;
        try {
            map.put("orderType", Order.ORDERTYPE_WEIXIN);
            result = orderService.order(map);
        } catch (Exception e) {
            e.printStackTrace();
            //预约失败
            return result;
        }
        if(result.isFlag()){
            //预约成功,短信通知
            String orderDate =(String)map.get("orderDate");
            try {
                SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE,telephone,orderDate);
                System.out.println("已经短信告知用户:"+telephone);
            } catch (ClientException e) {
                e.printStackTrace();
                //预约成功短信 下发失败
                System.out.println("短信下发失败:{短信签名:[预约成功]}");
            }
        }
        return result;
    }

    @RequestMapping("/findById")
    public Result findById(Integer id){
        try {
            Map map = orderService.findById(id);
            return  new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return  new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }

    }
}
